<template>
	<view class="main-box">
		<view :style="{ height:headBarInfo.navBarHeight+'px'}" class="head-bar-box">
			<view
				:style="{height:headBarInfo.headBarContentHeight+'px',marginRight:headBarInfo.headBarContentRight+'px'}"
				class="head-bar-content-box">

				<image :style="{marginLeft:headBarInfo.menuRight + 'px'}" style="height: 32px;width: 32px;"
					@click="backClick" src="../../../static/nav-bar-icon-back.png"></image>

				<view style="display: flex;align-items: center;flex: 1;margin-left: 8px;" @click="otherInfo(postData.userId)">
					<image class="head-bar-image" :src="postData.avatar"></image>
					<text class="head-bar-text">{{postData.nickname}}</text>
				</view>

				<button class="focus-btn" :class="{ followed: postData.isFollow }" @click="toggleFollow(postData)">
					{{ postData.isFollow ? '已关注' : '关注' }}</button>
			</view>

		</view>

		<scroll-view style="display: flex;flex-direction: column" scroll-y="true" @scrolltolower="getCommentList()"
			:style="{ height:scrollViewHeight+'px'}" ref="myScrollView">

			<uni-swiper-dot v-if="!playing" class="list-swiper-dot-box" :info="postData.imageList"
				:current="swiperCurrent" mode="dot" :dots-styles="dotsStyles" field="content">
				<swiper style="margin-bottom: 8px;height: 558rpx;width: 100%;" @change="change"
					:current="swiperDotIndex">
					<swiper-item v-for="(item,index) in postData.imageList">
						<view>
							<image style="width: 100%;background-color: white;height: 558rpx;" mode="aspectFill"
								:src="item"></image>
						</view>
					</swiper-item>
				</swiper>
				<view
					style="position: absolute;display: flex;flex-direction: column;bottom: 20px;left: 16px;width: 450rpx;">
					<view style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;">
						<text class="normal-text"
							style="color:#FFF;font-size: 17px;font-weight: 500;">{{postData.startRoute}}</text>
						<view style="width: 20px;height: 20px; margin: 0 8px 0 8px;">
							<image style="width: 20px;height: 20px;" src="../../../static/icon-goTo.png"></image>
						</view>
						<text class="normal-text"
							style="color:#FFF;font-size: 17px;font-weight: 500;">{{postData.endRoute}}</text>
					</view>
					<text class="normal-text"
						style="color: #ACACAC;font-size: 17px;font-weight: 500;">{{setDistanceText(postData.distance)}}</text>
				</view>

				<view
					style="position: absolute;display: flex;flex-direction: column;bottom: 20px;right: 16px;align-items: flex-end;">
					<text class="normal-text"
						style="color: #ACACAC;font-size: 17px;font-weight: 500;">{{postData.playCount}} 游玩人次</text>
					<button class="play-btn" @click="playingChange"
						:style="{backgroundColor:playBtnBgrColor}">{{playingBtnString}}</button>
					<image style="position: absolute;height: 19px;width: 15px;bottom: 3px;left: 12px;"
						src="../../../static/app-logo.png"></image>
				</view>

			</uni-swiper-dot>

			<map v-if="playing" style="width: 100%; height: 800rpx;" :polyline="mapPolyline"
				:latitude="routePolyline[0]" :markers="makerCovers" :longitude="routePolyline[1]">

			</map>
			<view v-if="playing"
				style="position: absolute;display: flex;flex-direction: column;top: 700rpx;right: 16px;align-items: flex-end;">
				<button class="play-btn" @click="playingChange"
					:style="{backgroundColor:playBtnBgrColor}">{{playingBtnString}}</button>
				<image style="position: absolute;height: 19px;width: 15px;bottom: 3px;left: 12px;"
					src="../../../static/app-logo.png"></image>
			</view>


			<view class="content-box">
				<view v-if="!playing"
					style="display: flex;flex-direction: column;align-items: flex-start;margin: 16px 16px 0 16px;">
					<text class="post-title" @click="testAudioPlay()">{{postData.title}}</text>
					<text class="post-content">{{postData.description}}</text>
					<text class="post-time">{{postData.createdTime}} {{postData.address.name}}</text>
					<view class="content-box-dividing-line">
					</view>
				</view>

				<view style="display: flex;flex-direction: column;align-items: flex-start;margin: 4px 16px 4px 16px;">

					<view style="display: flex;flex-direction: row;align-items: center;margin: 4px 0px;"
						v-for="(item,index) in routeArray">
						<image v-if="setRouteIcon(index)==0"
							style="height: 4px;width: 4px; background-color: #ACACAC;margin: 0 15.5px 0 4.5px;border-radius: 50%;">
						</image>

						<image v-if="setRouteIcon(index)==1"
							style="height: 14px;width: 11px;padding: 0px ;margin: 0 12px 0 1px;"
							src="../../../static/page-postDetails-icon-start.png"></image>

						<image v-if="setRouteIcon(index)==2"
							style="height: 14px;width: 11px;padding: 0px ;margin: 0 12px 0 1px;"
							src="../../../static/page-postDetails-icon-stop.png"></image>

						<text class="post-content" style="margin: 0 0 0 0px;">{{item.name}}</text>
					</view>

					<!-- <text>导航测试:{{testString}}</text> -->
				</view>

				<view v-if="!playing"
					style="display: flex;flex-direction: column;align-items: flex-start;margin: 4px 16px 4px 16px;">
					<view class="content-box-dividing-line" style="margin: 0 0 8px 0%;"></view>

					<view style="display: flex;flex-direction: row;margin: 4px 0 4px 0;"
						v-for="(item,index) in commentDataList">

						<view style="height: 32px;width: 32px;display: inline-table;">
							<image class="comments-avatar" :src="item.avatar"></image>
						</view>

						<view class="comments-center-box">
							<text style="color: #7B7B7B;font-size: 12px;" class="normal-text">
								{{item.nickName}}</text>
							<text style="color: #181818;font-size: 14px;padding-right: 62px;margin-top: 4px;"
								class="normal-text">
								{{item.content}}</text>
							<view style="display: flex;flex-direction: row;margin-top: 4px;">
								<text style="color: #ACACAC;font-size: 12px;" class="normal-text">
									{{item.createTime}}</text>
								<text style="color: #7B7B7B;font-size: 12px;margin-left: 8px;" class="normal-text"
									@click="setReplyTarget(item,-1)">
									回复</text>
							</view>

							<!-- 这里是二级评论 -->
							<view style="display: flex;flex-direction: row;margin: 4px 0 4px 0;"
								v-for="(childrenItem,childrenIndex) in item.children.list">

								<view style="height: 32px;width: 32px;display: inline-table;">
									<image class="comments-avatar" :src="childrenItem.avatar"></image>
								</view>

								<view class="comments-center-box">
									<text style="color: #7B7B7B;font-size: 12px;" class="normal-text">
										{{childrenItem.nickName}}</text>
									<text style="color: #181818;font-size: 14px;padding-right: 62px;margin-top: 4px;"
										class="normal-text">
										<text style="color: #2F6EF5;margin-right: 4px;">
											回复 @{{childrenItem.commentedUserName}}:</text>
										{{childrenItem.content}}
									</text>
									<view style="display: flex;flex-direction: row;margin-top: 4px;">
										<text style="color: #ACACAC;font-size: 12px;" class="normal-text">
											{{childrenItem.createTime}}</text>
										<text style="color: #7B7B7B;font-size: 12px;margin-left: 8px;"
											class="normal-text" @click="setReplyTarget(item,childrenIndex)">
											回复</text>
									</view>
								</view>

								<view class="comments-right-box">
									<image @click="fetchCommentLove(childrenItem)"
										style="height: 20px;width: 20px;margin-right: 8px;"
										:src="childrenItem.isCommentLove ? '/static/page-home-icon-like-after.png':'/static/page-home-icon-like.png'">
									</image>
									<text style="color: #7B7B7B;font-size: 14px;" class="normal-text">
										{{setNumberText(childrenItem.loveCount)}}</text>
								</view>

							</view>

							<view v-if="item.children.list.length <item.children.total"
								@click="getChildrenCommentList(item)"
								style="display: flex;flex-direction: row;font-size: 12px;align-items: center;color: #7B7B7B;font-weight: 400;margin-left: 5px;">
								展开更多内容 <image style="width: 10px;height: 5px;margin-left: 4px;"
									src="../../static/icon-moreComments.png"></image>
							</view>

							<!-- 这里是二级评论 -->

						</view>

						<view class="comments-right-box">
							<image @click="fetchCommentLove(item)" style="height: 20px;width: 20px;margin-right: 8px;"
								:src="item.isCommentLove ? '/static/page-home-icon-like-after.png':'/static/page-home-icon-like.png'">
							</image>
							<text style="color: #7B7B7B;font-size: 14px;" class="normal-text">
								{{setNumberText(item.loveCount)}}</text>
						</view>

					</view>

				</view>

			</view>

			<uni-load-more iconType="circle" :status="status" v-show="loadMoreShow" />

		</scroll-view>


		<view v-if="!playing"
			style="background-color: white;box-shadow:0 0px 30px 30px #f4f4f4;display: flex;flex-direction: row;padding-right: 6px;"
			id="myBottomView">
			<textarea style="margin: 12px 10px 12px 16px; background-color: white; ;height: 32px;flex: 1;
			border-radius: 12px;padding: 6px 12px  6px  12px;	border: 1px solid #E5E5E5;" type="textarea" suffixIcon="search"
				:placeholder="replyPlaceholder" v-model="inputString" @focus="setVisibleWhenFocus(false)"
				:focus="inputting" @blur="setVisibleWhenFocus(true)" auto-height @linechange="setViewData()"
				maxlength="128" confirm-type="send" @confirm="sendComment()">
			</textarea>


			<view v-if="bottomBtnsVisible" style="display: flex;align-items:center;color: #7B7B7B;margin-right: 10px;">
				<image @click="fetchPostLove()" style="height: 20px;width: 20px;margin-right: 8px;"
					:src="postData.isLove ? '/static/page-home-icon-like-after.png':'/static/page-home-icon-like.png'">
				</image>
				<text>{{setNumberText(postData.loveCount)}}</text>
				<image @click="fetchPostCollect()" style="height: 20px;width: 20px;margin-right: 8px;margin-left: 16px;"
					:src="postData.isCollect ? '/static/page-home-icon-search-collect-after.png':'/static/page-home-icon-search-collect.png'">
				</image>
				<text>{{setNumberText(postData.collectCount)}}</text>
				<image style="height: 20px;width: 20px;margin-right: 8px;margin-left: 16px;"
					src="/static/page-home-icon-comment.png"></image>
				<text>{{setNumberText(postData.commentCount)}}</text>
			</view>
		</view>

		<view v-if="playing" style="width: 100%;background-color: white;box-shadow:0 0px 30px 30px #f4f4f4;"
			id="myBottomView">
			<view style="margin: 18px;display: flex;
		flex-direction: column;">

				<text class="normal-text"
					style="color: #000;font-size: 16px;font-weight: 600;">正在前往{{routeArray[routeTarget].name}}</text>
				<text class="normal-text"
					style="color: #2F6EF5;font-size: 16px;font-weight: 600;margin-top: 12px;">{{routeSteps[nowStep].instruction}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getPostDetails,
		getCommentList,
		addComment,
		getChildrenCommentList,
		commentLove,
		postLove,
		postCollect,
		playPost

	} from '../../../api/posts';
	import {
		postFollow
	} from '../../../api/user';
	import QQMapWX from '../../../common/qqmap-wx-jssdk';
	var qqmapsdk;

	const plugin = requirePlugin("WechatSI");
	//创建InnerAudioContext音频对象。
	const innerAudioContext = wx.createInnerAudioContext();


	export default {
		data() {
			return {
				headBarInfo: {
					navBarHeight: 0, // 导航栏高度
					menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
					menuTop: 0, // 胶囊距顶部间距
					menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）

					headBarContentHeight: 0, //用来装载内容的盒子高度
					headBarContentRight: 0, //胶囊占据 的空间
				},
				scrollViewHeight: 0,

				//视图交互数据
				swiperCurrent: 0,
				dotsStyles: { //轮播图下表点样式
					bottom: 0,
					width: 4,
					height: 4,
					border: 'rgba(209, 209, 209, 1.0)',
					backgroundColor: 'rgba(209, 209, 209, 1.0)',
					selectedBorder: '0px',
					selectedBackgroundColor: 'rgba(0, 114, 237, 1.0) '
				},
				swiperDotIndex: 0,
				playing: false,
				playingBtnString: '游玩路线',
				playBtnBgrColor: '#2F6EF5',
				bottomBtnsVisible: true,
				status: 'more',
				loadMoreShow: false,
				//视图交互数据

				postId: 0,
				commentListpageNo: 1,
				commentListpageSize: 10,
				inputting: false, //是否聚焦输入
				inputString: '', //回复评论的输入内容
				replyPlaceholder: '说点什么吧~', //输入框站位字符
				replyData: {},
				/** 正在展示的评论总数据 **/
				commentData: {},
				/** 正在展示的评论数据数组 **/
				commentDataList: [],
				/** 自己新加入的评论 **/
				nowTempCommentList1: [],
				nowTempCommentList2: [],
				postData: {},
				/**帖子的路线规划地点信息数组**/
				routeArray: [],
				/**当前目标规划地点的下标**/
				routeTarget: 0,
				location: { //开始导航时当前地址
					latitude: 0,
					longitude: 0,
				},
				locationUpdateStartting: false, //实时定位是否正在使用
				//导航数据:
				/**导航路线点数组**/
				routePolyline: [],
				/**导航步骤路段数组**/
				routeSteps: [],
				nowStep: 0, //当前导航路段下标
				/**地图显示路线的数组，需要转化**/
				mapPolyline: [],
				direction: 0, //罗盘方向
				makerCovers: [],
				/**是否可以播报导航路线指示**/
				briefingRoute: true,
				/**是否可以播报导航转向指示**/
				briefingDirection: true,
				briefingSrc: [],
				testString: '',
				changeStepCd: 0,
				firstStepLimiteDst: 0,
			}
		},
		onLoad(option) {

			// 获取系统信息
			const systemInfo = wx.getSystemInfoSync();
			// 胶囊按钮位置信息
			const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
			// 导航栏高度 = 状态栏高度 + 44
			this.headBarInfo.navBarHeight = systemInfo.statusBarHeight + 44;
			this.headBarInfo.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
			this.headBarInfo.menuTop = menuButtonInfo.top;
			this.headBarInfo.menuHeight = menuButtonInfo.height;
			this.headBarInfo.headBarContentHeight = (this.headBarInfo.navBarHeight - this.headBarInfo.menuHeight - this
				.headBarInfo.menuTop) * 2 + this.headBarInfo.menuHeight;
			this.headBarInfo.headBarContentRight = menuButtonInfo.width + this.headBarInfo.menuRight * 2;

			this.setViewData()

			this.postId = option.postId
			this.replyData = {
				postId: this.postId,
				content: '',
				parentId: 0,
				rootCommentId: 0
			}

			this.getPostDetails()
			this.getCommentList()

			let that = this


			innerAudioContext.onEnded(function() {
				console.log("innerAudioContext.onEnded 播放结束  即将shift", JSON.stringify(that.briefingSrc))

				that.briefingSrc.shift()
				that.$nextTick(() => {
					if (that.briefingSrc.length > 0) {
						innerAudioContext.src = that.briefingSrc[0].filename
					}
				})

			})

			innerAudioContext.onCanplay(() => {
				console.log("innerAudioContext.onCanplay 可以播放 ", that.briefingSrc)
				that.$nextTick(() => {
					if (that.briefingSrc.length > 0) {
						that.audioPlay()
					}
				})


			});

			innerAudioContext.onPlay(() => {
				console.log("innerAudioContext.onPlay", that.briefingSrc)
			})

			innerAudioContext.onPause(() => {
				console.log("innerAudioContext.onPause", that.briefingSrc)
			})

			innerAudioContext.onStop(() => {
				console.log("innerAudioContext.onStop", that.briefingSrc)
			})

			innerAudioContext.onError(() => {
				console.log("innerAudioContext.onError", that.briefingSrc)
			})

			innerAudioContext.onWaiting(() => {
				console.log("innerAudioContext.onWaiting", that.briefingSrc)
			})

			innerAudioContext.onSeeked(() => {
				console.log("innerAudioContext.onSeeked", that.briefingSrc)
			})

		},
		onUnload() {
			this.endNavigation()
			uni.stopCompass()
			uni.stopLocationUpdate({
				type: "gcj02",
				success(res) {
					console.log("stopLocation_suc: ", res);
				},
				fail(err) {
					console.error("stopLocation_err: ", err);
				},
			})
			innerAudioContext.offEnded()
			innerAudioContext.offCanplay()
			// innerAudioContext.destroy()
		},

		methods: {
			otherInfo(userId){
				// 导航到别人主页
				uni.navigateTo({
				    url: `/packageMixture/pages/other/other?userId=${userId}`
				});
			},
			setViewData() {
				const systemInfo = wx.getSystemInfoSync();
				// 胶囊按钮位置信息
				const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
				var query = wx.createSelectorQuery();
				var bottomHeight = 0
				query.select('#myBottomView').boundingClientRect();
				let that = this
				query.exec(function(res) {
					//res就是 所有标签为mjltest的元素的信息 的数组
					//取高度

					bottomHeight = res[0].height
					that.scrollViewHeight = systemInfo.screenHeight - that.headBarInfo.navBarHeight - bottomHeight
					// console.log("this.scrollViewHeight", that.scrollViewHeight)
				});
			},
			change(e) {
				this.swiperCurrent = e.detail.current
			},
			backClick() {
				uni.navigateBack()
			},
			playingChange() {
				var checkLoginFunction = require('../../../common/chechLoginFunction.js')
				if (checkLoginFunction.checkLogin('cancel') == '') {
					return
				}

				this.playing = !this.playing

				if (this.playing) {
					this.playBtnBgrColor = '#EB5757'
					this.playingBtnString = '取消导航'
					this.fetchPlayPost()
					this.startNavigation()
					this.startLocationUpdate()

				} else {
					this.playBtnBgrColor = '#2F6EF5'
					this.playingBtnString = '游玩路线'
					this.endNavigation()

					uni.stopCompass()
					uni.stopLocationUpdate({
						type: "gcj02",
						success(res) {
							console.log("stopLocation_suc: ", res);
						},
						fail(err) {
							console.error("stopLocation_err: ", err);
						},
					})
					uni.offLocationChange()
				}

				var that = this
				this.$nextTick(function() {
					that.setViewData()
				})
			},
			setVisibleWhenFocus(visible) {
				this.bottomBtnsVisible = visible
				this.inputting = !visible;
				if (this.inputString.length == 0 && this.inputting == false) {
					// console.log("聚焦退出")
					this.replyPlaceholder = '说点什么吧~'
					this.replyData = {
						postId: this.postId,
						content: ''
					}
				}
			},
			setNumberText(count) {
				if (count > 99) {
					return '99+';
				} else if (count == null) {
					return 0;
				} else {
					return count;
				}
			},
			setDistanceText(distance) {
				if (distance > 1000) {
					var distanceString = (distance / 1000).toFixed(1)

					return '约' + distanceString + '公里'
				} else {
					return '约' + distance + '米'
				}
			},
			setRouteIcon(index) {
				if (index == this.routeTarget) {
					return 1
				} else if (index == this.routeArray.length - 1 && this.routeTarget != this.routeArray.length) {
					return 2
				} else {
					return 0
				}
			},
			getDistance(lat1, lng1, lat2, lng2) {
				let a = Math.PI / 180;
				let s = Math.acos(Math.cos(lat1 * a) * Math.cos(lat2 * a) * Math.cos(lng1 * a - lng2 * a) + Math.sin(lat1 *
					a) * Math.sin(lat2 * a))
				s = s * 6378.137 // EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000;
				return parseFloat((s * 1000).toFixed(1));
			},


			getPostDetails() {

				getPostDetails(this.postId).then(res => {
					console.log("请求成功:", res)
					this.postData = res.data
					this.routeArray = res.data.route
					this.setMapPolyline(1)
					this.setMakerPost()
				}).catch(err => {
					console.log("请求失败:", err)

				});
			},
			fetchPlayPost() {
				const data = {
					postId: parseInt(this.postId)
				}

				playPost(data).then(res => {
					console.log("请求游玩帖子成功：", res, data)
					if (res.code == 0) {
						this.postData.playCount = res.data.playCount
					}

				}).catch(err => {
					console.log("请求游玩帖子失败：", err, data)
				})
			},
			startNavigation() {
				console.log("开始导航startNavigation")
				uni.getLocation({
					type: 'gcj02', // 比较精确
					success: (res) => {
						this.location.latitude = res.latitude
						this.location.longitude = res.longitude
						//获取当前经纬度后开始获取导航路线
						this.getDirectionRoute()
					},
					fail: (res) => {
						console.log(res)
					}
				})

			},
			endNavigation() {
				console.log("结束导航endNavigation")
				//结束导航
				this.locationUpdateStartting = false
				this.briefingDirection = true
				this.briefingRoute = true
				this.changeStepCd = 0;
				this.briefingSrc = [];
				this.nowStep = 0 //清空导航步骤下标防止下次导航时错乱
			},
			/**获取导航路线并开始导航**/
			getDirectionRoute() {

				var lat1 = this.location.latitude
				var lon1 = this.location.longitude
				var lat2 = this.routeArray[this.routeTarget].latitude
				var lon2 = this.routeArray[this.routeTarget].longitude
				let that = this
				uni.request({
					url: 'https://apis.map.qq.com/ws/direction/v1/walking?from=' + lat1 + ',' + lon1 +
						'&to=' + lat2 + ',' + lon2 +
						'&key=VEPBZ-UJ4KQ-IAS5R-4U2CW-F4372-SBBAI',

					success: (res) => {
						console.log("获取导航成功：", res.data.result)

						that.routePolyline = res.data.result.routes[0].polyline
						that.routeSteps = res.data.result.routes[0].steps
						var coors = that.routePolyline;
						for (var i = 2; i < coors.length; i++) {
							coors[i] = coors[i - 2] + coors[i] / 1000000
						}
						// console.log("routePolyline解析地址：", that.routePolyline)
						// console.log("routeSteps导航步骤：", that.routeSteps)


						that.firstStepLimiteDst = that.getDistance(that.routePolyline[0], that.routePolyline[
							1], lat1, lon1) + 100;
						console.log("刚开始导航保护距离(防止特殊起点导致的重复获取导航)", that.firstStepLimiteDst)
						//在地图上展示导航路线
						while (that.mapPolyline.length > 1) {
							that.mapPolyline.pop()
						}
						that.setMapPolyline(2)
						that.setMapPolyline(3)
						that.audioPlayRoute(that.routeSteps[that.nowStep].instruction)

					},
					fail: (err) => {
						console.log("获取导航成失败：", err)
					}
				})

			},
			startLocationUpdate() {

				let that = this
				uni.startLocationUpdate({
					type: "gcj02",
					success(res) {
						that.locationUpdateStartting = true
						console.log("startLocation_suc: ", res);
					},
					fail(err) {
						console.log("startLocation_err: ", err);
						// console.error("startLocation_err: " + JSON.stringify(err));
					},
				})

				uni.startCompass() //开始罗盘监听获取手机方向

				uni.onCompassChange(function(res) {
					that.direction = res.direction.toFixed(0)
				})

				uni.onLocationChange(function(res) {
					if (that.routePolyline.length == 0) {
						return
					}

					// console.log('纬度：' + res.latitude);
					// console.log('经度：' + res.longitude);
					var nowLat = res.latitude
					var nowLon = res.longitude

					that.setMakerNavigation(nowLat, nowLon)

					var polylineIdxNowStep = that.routeSteps[that.nowStep].polyline_idx //当前导航路段对应地点的数组下标

					// console.log("查看终点下标: ", polylineIdxNowStep[1]);
					var distanceNowToCenter = 1000 //当前经纬度与当前导航路段终点的距离(默认够高防止识别错误)已改为中点
					var distanceNowToCenterClose = 10000 //当前经纬度与最近导航路段终点的距离用于纠正  已改为中点
					var routeStepsIdxClose = 0 //当前经纬度与最近导航路段终点的地点下标
					var awayFromRoute = 1000
					var distanceNowToEnd = 1000;
					var distanceNowToRouteEnd = that.getDistance(nowLat, nowLon, that.routePolyline[that
						.routePolyline.length - 2], that.routePolyline[that.routePolyline.length - 1])

					for (var i = 0; i < that.routeSteps.length; i++) {

						var lat0 = that.routePolyline[(that.routeSteps[i].polyline_idx)[0]]
						var lon0 = that.routePolyline[(that.routeSteps[i].polyline_idx)[0] + 1]

						var lat1 = that.routePolyline[(that.routeSteps[i].polyline_idx)[1] - 1]
						var lon1 = that.routePolyline[(that.routeSteps[i].polyline_idx)[1]]

						var latAvg = (lat0 + lat1) / 2
						var lonAvg = (lon0 + lon1) / 2
						// console.log("查看修改数据：latAvg,lonAvg,distance,endLat0,endLon0,endLat1,endLon1", latAvg,
						// 	lonAvg, distance, endLat0, endLon0, endLat1, endLon1)

						var distance = that.getDistance(nowLat, nowLon, latAvg, lonAvg)
						if (i == that.nowStep) {
							distanceNowToCenter = distance
							distanceNowToEnd = that.getDistance(nowLat, nowLon, lat1, lon1)
						}
						if (distance < distanceNowToCenterClose && i != that.nowStep) {
							distanceNowToCenterClose = distance
							routeStepsIdxClose = i
						}
					}
					// console.log("计算远离距离: step：", that.nowStep, nowLat, nowLon)
					var nowAwayDst = that.calCloseDistance(that.routePolyline, that.routeSteps[that.nowStep]
						.polyline_idx, nowLat, nowLon)
					// console.log("计算远离距离: routeStepsIdxClose：", routeStepsIdxClose, nowLat, nowLon)
					var closeAwayDst = that.calCloseDistance(that.routePolyline, that.routeSteps[
						routeStepsIdxClose].polyline_idx, nowLat, nowLon)

					that.testString = "当前远离:" + nowAwayDst + " 最近其他远离:" + closeAwayDst +
						" 当前距离中中心:" + distanceNowToCenter + " 最近其他距离中心:" +
						distanceNowToCenterClose + " 当前步骤:" + that.nowStep + " 最近其他步骤:" +
						routeStepsIdxClose + "当前路段距离终点：" + distanceNowToEnd + "当前导航终点距离终点" + distanceNowToRouteEnd;

					that.changeStepCd++;
					var limitCd = 4
					var date = new Date();


					console.log("CD", that.changeStepCd, "定位变化： distanceNowToEnd < 20:", distanceNowToEnd < 20,
						"  closeAwayDst < nowAwayDst: ", closeAwayDst < nowAwayDst, closeAwayDst, nowAwayDst,
						date)

					if (distanceNowToRouteEnd < 20) {
						if (that.changeStepCd < limitCd) {
							return;
						}
						console.log("导航终点触发")
						that.changeStep(-2)
						that.changeStepCd = 0
						return
					}

					if (distanceNowToEnd < 25) { //当前导航路段终点20米范围内开始进入下一个导航路段
						if (that.changeStepCd < limitCd) {
							return;
						}
						console.log("路段终点触发")

						//播放转向语音
						if (that.routeSteps[that.nowStep].act_desc != "") {
							that.audioPlayDierection(that.routeSteps[that.nowStep].act_desc)
						}

						that.changeStepCd = 0
						return;

					} else if (closeAwayDst < nowAwayDst) { //自动修正导航步骤
						if (that.changeStepCd < limitCd) {
							return;
						}
						console.log("自动修正导航步骤触发")

						that.changeStep(routeStepsIdxClose)

						that.changeStepCd = 0
						return;
					} else if (nowAwayDst > 100) { //一百米范伟远离检测，过于远离直接重新导航
						if (that.changeStepCd < limitCd) {
							return;
						}

						if (that.nowStep == 0 && nowAwayDst < that.firstStepLimiteDst) {
							return;
						}
						that.handleStart("您已偏离航线，正在为您重新规划路线")
						console.log("一百米范伟远离检测触发")
						that.endNavigation()
						that.startNavigation()

						that.changeStepCd = 0
						return;
					}


				});
				uni.onLocationChangeError(function(res) {
					console.log('实时定位出错：' + res);
				});
			},


			changeStep(stepIdx) {

				let that = this;
				console.log("changeStep:开始进入导航步骤：" + stepIdx + "原为：" + this.nowStep)
				this.briefingDirection = true
				this.briefingRoute = true


				if (stepIdx == -2) { //到达目的地
					//播报语音

					//判断是否还有下一个导航目标
					if (this.routeTarget == this.routeArray.length - 1) { //无下一个目标

						this.routeTarget = 0

						setTimeout(function() {
							uni.showToast({
								title: '您已完成全部规划路线游玩！！',
								duration: 2000
							})
							that.handleStart("到达导航终点,您已完成全部规划路线游玩")
							that.endNavigation()
						}, 500)

						this.playingChange()

					} else {
						this.audioPlayDierection("到达导航终点")
						uni.showToast({
							title: '开始自动导航到下一个路线目标',
							duration: 2000
						})
						this.routeTarget = this.routeTarget + 1

						setTimeout(function() {
							console.log("开始自动导航到下一个路线目标")
							that.handleStart("开始自动导航到下一个路线目标")
							that.setMapPolyline(1)
							that.endNavigation()
							that.startNavigation()
						}, 500)

					}

					this.nowStep = 0


				} else { //如果输入不为-1,则跳到目标stepIdx导航路段
					if (stepIdx == -1) {
						this.nowStep++
						this.audioPlayRoute(that.routeSteps[this.nowStep].instruction) //播报语音
						this.setMapPolyline(3)
					} else {
						this.nowStep = stepIdx
						this.audioPlayRoute(that.routeSteps[this.nowStep].instruction) //播报语音
						this.setMapPolyline(3)
					}

				}

			},
			/** 在地图上画下路线 */
			setMapPolyline(type) {

				switch (type) {
					case 1:
						this.mapPolyline = []
						this.mapPolyline.push({
							points: this.postData.polyline,
							color: '#2F6EF5',
							width: 6,
							borderColor: '#2f693c',
							borderWidth: 1,
							level: 'aboveroads'
						})
						break;

					case 2:
						if (this.mapPolyline.length == 1) {
							var plRoute = [];
							for (var i = 0; i < this.routePolyline.length; i += 2) {
								plRoute.push({
									latitude: this.routePolyline[i],
									longitude: this.routePolyline[i + 1]
								})
							}
							this.mapPolyline.push({
								points: plRoute,
								color: '#d3ecd8',
								width: 6,
								borderColor: '#2f693c',
								borderWidth: 1,
								level: 'abovebuildings'
							})
						} else if (this.mapPolyline.length == 2) {

							var plRoute = [];
							for (var i = 0; i < this.routePolyline.length; i += 2) {
								plRoute.push({
									latitude: this.routePolyline[i],
									longitude: this.routePolyline[i + 1]
								})
							}
							this.mapPolyline[1].points = plRoute


						}
						break;

					case 3:
						if (this.mapPolyline.length == 2) {


							var plRouteNow = [];
							var indexSrc = this.routeSteps[this.nowStep].polyline_idx

							for (var i = indexSrc[0]; i < indexSrc[1]; i += 2) {
								plRouteNow.push({
									latitude: this.routePolyline[i],
									longitude: this.routePolyline[i + 1]
								})
							}

							this.mapPolyline.push({
								points: plRouteNow,
								color: '#4cdd6e',
								width: 6,
								borderColor: '#2f693c',
								borderWidth: 1,
								level: 'abovelabels'
							})

						} else if (this.mapPolyline.length > 2) {
							var plRouteNow = [];
							var indexSrc = this.routeSteps[this.nowStep].polyline_idx

							for (var i = indexSrc[0]; i < indexSrc[1]; i += 2) {
								plRouteNow.push({
									latitude: this.routePolyline[i],
									longitude: this.routePolyline[i + 1]
								})
							}

							this.mapPolyline[2].points = plRouteNow
						}
						break;

					default:
						break;
				}
				// console.log("在地图上画下路线length:  , routeSteps:", this.mapPolyline.length,this.routeSteps[this.nowStep].polyline_idx)
				// console.log("在地图上画下路线 类型：", type, this.mapPolyline)

			},
			/** 设置规划点的标志 */
			setMakerPost() {
				this.makerCovers = []
				for (let routeOne of this.routeArray) {
					// console.log("设置规划点的标志",routeOne)
					this.makerCovers.push({
						//标记maker
						id:routeOne.index,
						latitude: routeOne.latitude,
						longitude: routeOne.longitude,
						// iconPath: '../../../static/page-postDetails-icon-start.jpg',
						width: '20px',
						height: '30px',
						alpha: 1,
						// callout: {		
						// 	content: routeOne.name, //文本
						// 	color: '#2f2f2f', //文本颜色
						// 	borderRadius: 3, //边框圆角
						// 	borderWidth: 1, //边框宽度
						// 	borderColor: '#FF0202', //边框颜色
						// 	bgColor: '#ffffff', //背景色
						// 	padding: 5, //文本边缘留白
						// 	textAlign: 'center' //文本对齐方式  left, right, center
						// },

						label: {
							content: routeOne.name,
							fontSize: 10,
							borderRadius: 5,
							padding: 5,
							textAlign: 'center',
							color: '#2f2f2f',
							bgColor: '#ffffff',
							anchorX: -(parseInt((routeOne.name.length/2).toFixed(0))-5)
						},

					})
				}

			},
			/** 设置导航的实时位置标志 */
			setMakerNavigation(lat, lon, direction) {

				if (this.makerCovers.length <= this.routeArray.length) {
					this.makerCovers.push({
						latitude: lat,
						longitude: lon,
						iconPath: "../../../static/icon-direction.png",
						width: '40px',
						height: '40px',
						rotate: this.direction,
						anchor: {
							x: 0.5,
							y: 0.5
						}
					})
				} else {
					this.makerCovers[this.makerCovers.length - 1].latitude = lat
					this.makerCovers[this.makerCovers.length - 1].longitude = lon
					this.makerCovers[this.makerCovers.length - 1].rotate = this.direction
				}

			},
			calCloseDistance(polyline, polyline_idx, nowLat, nowLon) {

				var s = polyline_idx[0]
				var e = polyline_idx[1] - 1

				var resultDst = 1000
				for (var i = s; i < e; i = i + 2) {

					var distance = this.getDistance(nowLat, nowLon, polyline[i], polyline[i + 1])
					// console.log("计算过程: s , e ,i ,distance ,resultDst", s, e, i, distance, resultDst)
					if (distance < resultDst) {
						resultDst = distance
					}
				}

				return resultDst;
			},
			audioPlayRoute(contentString) {
				if (this.briefingRoute) {
					this.handleStart(contentString)
					this.briefingRoute = false
				}
			},
			audioPlayDierection(contentString) {
				if (this.briefingDirection) {
					this.handleStart(contentString)
					this.briefingDirection = false
				}
			},
			//文字转语音
			handleStart(string) {
				const that = this
				if (string.length > 0) {
					plugin.textToSpeech({
						lang: "zh_CN",
						tts: true,
						content: string,
						success: (res) => {
							console.log("文字转语音 :", res.origin)

							that.briefingSrc.push(res);
							// innerAudioContext.onPlay((e) =>{
							// 		console.log("文字转语音 :innerAudioContext.onPlay", res.origin)
							// })

							that.$nextTick(() => {
								console.log("文字转语音 : that.briefingSrc", that.briefingSrc)
								if (that.briefingSrc.length == 1) {
									console.log("文字转语音 : that.briefingSrc.length == 1", that
										.briefingSrc)
									innerAudioContext.src = that.briefingSrc[0].filename;
									console.log("文字转语音 : innerAudioContext.src", innerAudioContext.src)
								}
							})



						},
						fail: (res) => {
							console.log("handleStart fail", res);
						},
					});
				}

			},
			//播放语音
			audioPlay() {
				// if()
				if (this.briefingSrc.length == 0) {
					console.log(`暂无语音`);
					return;
				}

				//播放音频
				innerAudioContext.play();
				console.log(`开始播放:`, this.briefingSrc[0].origin);

			},
			getCommentList() {
				this.loadMoreShow = true;
				if (this.status == 'no-more') {
					setTimeout(() => {
						this.loadMoreShow = false;

					}, 1000)
					return;
				}
				this.status = 'loading';

				const data = {
					postId: this.postId,
					pageNo: this.commentListpageNo,
					pageSize: this.commentListpageSize,
				}

				getCommentList(data).then(res => {
					console.log("getCommentList成功：", res)
					this.loadMoreShow = false;
					if (this.commentListpageNo == 1) {
						this.commentData = res.data;
						this.commentDataList = this.commentData.list
					} else {
						for (var i = 0; i < res.data.list.length; i++) {
							var flag = false

							for (let item of this.nowTempCommentList1) {
								if (item.id == res.data.list[i].id) {
									flag = true;
								}

							}


							if (flag == false) {
								this.commentDataList.push(res.data.list[i])
							}

						}

					}
					if (this.commentDataList.length >= this.commentData.total) {
						this.status = 'no-more';
					}

					console.log("getCommentList请求成功:", res.data)
					this.commentListpageNo++
				}).catch(err => {
					this.loadMoreShow = false;
					console.log("getCommentList请求失败:", err)

				});


			},
			getChildrenCommentList(root) {

				const pageNo = parseInt((root.children.list.length / 5).toFixed(0)) + 1
				const data = {
					rootCommentId: root.id,
					pageNo: pageNo,
					postId: this.postId
				}
				console.log("getChildrenCommentList", root, data, )
				getChildrenCommentList(data).then(res => {
					console.log("getChildrenCommentList请求成功:", res)

					for (var i = 0; i < res.data.list.length; i++) {
						var flag = false
						for (let item of this.nowTempCommentList2) {
							if (item.id == res.data.list[i].id) {
								flag = true

							}
						}
						if (flag == false) {
							root.children.list.push(res.data.list[i])
						}

					}
					root.children.pages = res.data.pages;
					root.children.total = res.data.total;
				}).catch(err => {
					console.log("getChildrenCommentList请求失败:", err)
				});
			},
			setReplyTarget(parent, rootIndex) {
				var checkLoginFunction = require('../../../common/chechLoginFunction.js')
				if (checkLoginFunction.checkLogin('cancel') == '') {
					return
				}


				if (this.inputting == true) return;

				console.log('点击了回复', parent, rootIndex)
				if (rootIndex == null) {
					this.inputting = true;
					this.replyPlaceholder = '说点什么吧~'
					this.replyData = {
						postId: this.postId,
						content: '',
						parentId: 0,
						rootCommentId: 0
					}
				} else if (rootIndex == -1) { //目标评论和顶级评论是同一个
					this.inputting = true;
					this.replyPlaceholder = '回复 @' + parent.nickName
					this.replyData = {
						postId: this.postId,
						content: '',
						parentId: parent.id,
						rootCommentId: parent.id
					}
				} else {
					const root = parent.children.list[rootIndex]

					this.inputting = true;
					this.replyPlaceholder = '回复 @' + root.nickName
					this.replyData = {
						postId: this.postId,
						content: '',
						parentId: root.id,
						rootCommentId: parent.id
					}
				}

			},
			sendComment() {
				var checkLoginFunction = require('../../../common/chechLoginFunction.js')
				if (checkLoginFunction.checkLogin('cancel') == '') {
					return
				}

				let that = this;
				that.replyData.content = that.inputString;
				console.log("发送", that.replyData)


				addComment(that.replyData).then(res => {
					console.log("创建评论成功", res, that.commentDataList)
					if (res.code != 0) {
						return;
					}
					const newComment = res.data;

					if (newComment.rootCommentId == 0) {
						newComment.children = {
							list: [],
							pages: 0,
							total: 0
						}
						that.commentDataList.unshift(newComment)
						that.nowTempCommentList1.push(newComment);
					} else {


						for (var i = 0; i < that.commentDataList.length; i++) {
							// console.log("创建评论成功:查看插入过程", that.commentDataList[i])
							if (newComment.rootCommentId == that.commentDataList[i].id) {
								const list = that.commentDataList[i].children.list
								list.push(newComment);
								that.commentDataList[i].children.total++;
								that.nowTempCommentList2.push(newComment);
								// console.log("创建评论成功:查看插入", list)
							}
						}
					}

					console.log("创建评论成功:查看插入结果", that.commentDataList, that.nowTempCommentList1, that
						.nowTempCommentList2)


				}).catch(err => {
					console.log("创建评论失败", err)
				});

				this.$nextTick(() => {
					this.inputString = '';
					this.inputting = false
				})

			},

			async toggleFollow(postData) {

				var checkLoginFunction = require('../../../common/chechLoginFunction.js')
				if (checkLoginFunction.checkLogin('cancel') == '') {
					return
				}

				const userId = uni.getStorageSync('userId');
				// 在此处理实际的关注或取消关注逻辑，如发起 API 请求

				const data = {
					followedId: postData.userId,
					isFollow: !postData.isFollow,
				};

				console.log("toggleFollow点击关注", postData, data)

				await postFollow(data)
					.then(response => {
						console.log('toggleFollow 点击关注', data, response)
						if (response.message == "ok") {
							postData.isFollow = !postData.isFollow;
						} else {

						}
					})
					.catch(error => {
						console.error('点赞失败:', error);
					});
			},
			fetchPostLove() {


				console.log('fetchPostLove', this.postData.isLove)
				const data = {
					isLove: !this.postData.isLove,
					nickname: this.postData.nickname,
					postId: this.postData.id,
					title: this.postData.title,
					userId: this.postData.userId
				};
				postLove(data).then(res => {
					console.log("postLove 点击点赞", data, res)
					if (res.code != 0) {
						return
					}
					this.postData.isLove = !this.postData.isLove;
					if (this.postData.isLove == true) {
						this.postData.loveCount++;
					} else {
						this.postData.loveCount--;
					}
				}).catch(err => {
					console.log("postLove 点击点赞", err)
				})

			},
			fetchPostCollect() {

				console.log('fetchPostCollect', this.postData.isCollect)

				const data = {
					isCollect: !this.postData.isCollect,
					nickname: this.postData.nickname,
					postId: this.postData.id,
					title: this.postData.title,
					userId: this.postData.userId
				};
				postCollect(data).then(res => {
					console.log("postCollect 点击收藏", data, res)
					if (res.code != 200) {
						return
					}
					this.postData.isCollect = !this.postData.isCollect;
					if (this.postData.isCollect == true) {
						this.postData.collectCount++;
					} else {
						this.postData.collectCount--;
					}

				}).catch(err => {
					console.log("postCollect 点击收藏", err)
				})
			},
			fetchCommentLove(comment) {
				const data = {
					commentId: comment.id,
					isLove: !comment.isCommentLove
				};


				console.log('fetchCommentLove', comment)

				commentLove(data).then(res => {
					console.log("fetchCommentLove 点击点赞", data, res)
					if (res.message != "ok") {
						return
					}
					comment.isCommentLove = !comment.isCommentLove;
					if (comment.isCommentLove == true) {
						comment.loveCount++;
					} else {
						comment.loveCount--;
					}
				}).catch(err => {
					console.log("fetchCommentLove 点击点赞", err)
				})
			},
			testAudioPlay() {
				// console.log("测试")
				// this.changeStepCd = 4;
				// this.changeStep(-1)
				// this.audioPlayRoute(this.routeSteps[this.nowStep].instruction)
				const newOne = {
					avatar: "https://file-1329375573.cos.ap-nanjing.myqcloud.com/user_avatar/v6dMeDUc-am6WDg9ZUAOl09d43c7a991a0f0963a481fdf1fa1f01.jpg?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDxjIk2GG9rNgnfJk3A4lEVZQ4aswnQoyv%26q-sign-time%3D1732007334%3B1763543334%26q-key-time%3D1732007334%3B1763543334%26q-header-list%3Dhost%26q-url-param-list%3D%26q-signature%3D8b153f7025147f0460dc3c99b63f1b2cb78c76e5",
					commentLevel: null,
					commentedUserName: null,
					content: "23:27：1",
					createTime: "2024-11-21 23:27:44",
					id: 52,
					isCommentLove: false,
					loveCount: 0,
					nickName: "用户9b1",
					parentId: 0,
					postId: 29,
					rootCommentId: 0,
					userId: 5
				}
				this.commentDataList.unshift(newOne)
				console.log('testAudioPlay', this.commentDataList)
			}


		}
	}
</script>

<style>
	.main-box {
		position: absolute;
		bottom: 0%;
		top: 0%;
		right: 0%;
		left: 0%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.head-bar-box {
		width: 100%;
		background-color: white;
		display: flex;
		flex-direction: column-reverse;
		border-bottom: 1px solid #D9D9D9
	}

	.head-bar-content-box {
		background-color: #fff;
		align-items: center;
		display: flex;
		justify-content: space-between;
	}

	.head-bar-image {
		height: 32px;
		width: 32px;
		border-radius: 50%;
		display: inline-table;
	}

	.head-bar-text {
		color: #181818;
		margin-left: 12rpx;
		text-overflow: ellipsis;
		overflow: hidden;
		-webkit-box-orient: vertical;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		text-align: start;
		font-size: 17px;
		font-style: normal;
		font-weight: 500;
		line-height: 150%;
	}

	.focus-btn {
		min-width: 60px;
		margin: 0 14rpx 0 14rpx;
		border-radius: 50%;
		color: #FFF;
		background-color: #2F6EF5;
		font-size: 14px;
		height: 28px;
		flex-shrink: 0;
		align-items: center;
		border-radius: 20px;
		display: flex
	}

	.focus-btn.followed {
		background-color: transparent;
		/* 关注后的背景透明，模拟镂空效果 */
		color: #ACACAC;
		/* 文字颜色变为灰色 */
		border: 1px solid #ACACAC;
		/* 灰色边框 */
		font-size: 24rpx;
		padding: 10rpx 20rpx;
		/* 调整 padding 保持一致 */
	}

	.play-btn {
		border-radius: 50%;
		color: #FFF;
		background-color: #2F6EF5;
		font-size: 17px;
		width: 115px;
		height: 28px;
		flex-shrink: 0;
		align-items: center;
		border-radius: 20px;
		display: flex;
		justify-content: flex-end;

	}

	.content-box-dividing-line {
		height: 1px;
		width: 100%;
		left: 2px;
		right: 2px;
		margin: 12px 0px 0 0;
		background-color: #DDD;
	}

	.post-title {
		color: #181818;
		text-align: center;
		font-size: 17px;
		font-style: normal;
		font-weight: 400;
		line-height: 150%;
		/* 25.5px */
	}

	.post-content {
		color: #181818;
		font-family: "PingFang SC";
		font-size: 14px;
		font-style: normal;
		font-weight: 400;
		line-height: 150%;
		margin: 10px 0px 0 0px;
	}

	.post-time {
		color: #ACACAC;
		font-family: "PingFang SC";
		font-size: 12px;
		font-style: normal;
		font-weight: 400;
		line-height: 150%;
		margin: 12px 0px 0 0px;
	}

	.comments-avatar {
		height: 32px;
		width: 32px;
		border-radius: 50%;
		display: inline-table;
	}

	.comments-center-box {
		display: flex;
		flex-direction: column;
		margin: 0px 0px 0px 8px;
	}

	.comments-right-box {
		display: flex;
		flex-direction: row;
		margin-top: 12px;
		position: absolute;
		right: 16px;
	}

	.normal-text {
		font-style: normal;
		font-weight: 400;
		line-height: 150%;
	}

	.send-btn {
		font-size: 14px;
		position: absolute;
		color: #fff;
		background-color: #DDD;
		font-size: 14px;
		width: 60px;
		height: 28px;
		flex-shrink: 0;
		align-items: center;
		display: flex;
		border-radius: 8px;
		display: flex;
		bottom: 15px;
		right: 19px;
		z-index: 10;
	}
</style>